package com.system.insurance.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.common.result.Result;
import com.system.insurance.entity.AppletUser;
import com.system.insurance.entity.Frequency;
import com.system.insurance.service.AppletUserService;
import com.system.insurance.service.FrequencyService;
import com.system.insurance.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.annotation.WebFilter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 微信/PC用户 前端控制器
 * </p>
 *
 * @author WS
 * @since 2024-05-09
 */
@RestController
@Api(tags = "小程序pc用户")
@RequestMapping("/insurance/applet-user")
public class AppletUserController {

@Autowired
    private AppletUserService appletUserService;

    @Autowired
    private WXPhoneLogin wxPhoneLogin;


    @Autowired
    private FrequencyService frequencyService;

//    @Autowired(required = true)
//    private RestTemplate restTemplate;

    @ApiOperation("获取头像和昵称")
    @PostMapping("/getHeadAndName")
    public Result getHeadAndName(@RequestBody LoginDto loginDto) {
        //判断客户端传的code是否为空
        if (loginDto.getCode() == null) {
            return Result.fail().message("code不能为空");
        }
        LoginDto login = wxPhoneLogin.appWxLogin(loginDto.getCode());
        QueryWrapper<AppletUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", login.getOpenid());
        AppletUser appletUser1 = appletUserService.getOne(queryWrapper);
        if (appletUser1 == null) {
            AppletUser appletUser = new AppletUser();
            String randomCharacters = AppletUserController.getRandomCharacters(6);
            appletUser.setNickName(randomCharacters);

            appletUser.setOpenid(login.getOpenid());
            appletUser.setCreateTime(LocalDateTime.now());
            boolean save = appletUserService.save(appletUser);

            Frequency frequency = new Frequency();
            frequency.setAppletuserid(appletUser.getId());
            frequency.setEnquiry(3);
            frequency.setOffer(3);
            boolean save1 = frequencyService.save(frequency);


            Map<String, Object> cliams = new HashMap<>();
            cliams.put("id",appletUser.getId());
            String token = JwtUtils.generateJwt(cliams);
            return Result.ok(token).message("登陆成功");
        } else {
            appletUser1.setUpdateTime(LocalDateTime.now());
            appletUserService.updateById(appletUser1);
            //生成token
            Map<String, Object> cliams = new HashMap<>();
            cliams.put("id",appletUser1.getId());
            String token = JwtUtils.generateJwt(cliams);
            return Result.ok(token).message("登陆成功");
        }
    }


    @PostMapping("/wx/getPhone")
    public Result<Object> getPhone(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "openid") String openid) throws Exception{
        JSONObject token = WechatUtil.getAccessToken();

        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("code", code);
//        ResponseEntity<JSONObject> wxResult = restTemplate.postForEntity(url, paramMap, JSONObject.class);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        String reqJsonStr = JsonUtil.objToString(jsonObject);

        JSONObject phone;
        phone = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));
//        JSONObject phoneInfo = wxResult.getBody().getJSONObject("phone_info");
        LambdaQueryWrapper<AppletUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppletUser::getOpenid, openid);
        AppletUser one = appletUserService.getOne(wrapper);
        if (one != null) {
            phone.get("phoneNumber");
            appletUserService.updateById(one);
        }
        return Result.ok(one);
    }


//    @PostMapping("/wx/getPhone")
//    public Result getPhone(@RequestBody LoginDto loginDto) {
//        //判断客户端传的code是否为空
//        if (loginDto.getCode() == null) {
//            return Result.fail().message("code不能为空");
//        }
//        LoginDto login = wxPhoneLogin.appWxLogin(loginDto.getCode());
//            JSONObject access_token = WechatUtil.getAccessToken();
//            // 使用前端code获取手机号码 参数为json格式
//            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token.getString("access_token");
//            Map<String, String> paramMap = new HashMap<>();
//            paramMap.put("code", loginDto.getCode());
//            ResponseEntity<JSONObject> wxResult = restTemplate.postForEntity(url, paramMap, JSONObject.class);
//            JSONObject phoneInfo = wxResult.getBody().getJSONObject("phone_info");
//            Object phoneNumber = phoneInfo.get("phoneNumber");
//
//            QueryWrapper<AppletUser> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("phone", phoneNumber.toString());
//            AppletUser appletUser1 = appletUserService.getOne(queryWrapper);
//            if (appletUser1 == null) {
//
//                AppletUser appletUser = new AppletUser();
//                String randomCharacters = AppletUserController.getRandomCharacters(6);
//                appletUser.setNickName(randomCharacters);
//                appletUser.setPhone(phoneNumber.toString());
//                appletUser.setCreateTime(LocalDateTime.now());
//                boolean save = appletUserService.save(appletUser);
//                Map<String, Object> cliams = new HashMap<>();
//                cliams.put("id", appletUser.getId());
//                String token = JwtUtils.generateJwt(cliams);
//                return Result.ok(token).message("登陆成功");
//            }else {
//                appletUser1.setUpdateTime(LocalDateTime.now());
//                appletUserService.updateById(appletUser1);
//                //生成token
//                Map<String, Object> cliams = new HashMap<>();
//                cliams.put("id",appletUser1.getId());
//                String token = JwtUtils.generateJwt(cliams);
//                return Result.ok(token).message("登陆成功");
//            }
//    }

    public static String getRandomCharacters(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 生成用户本人邀请二维码
     * @param appUserId
     * @return
     */
    public static Map<String, Object> getminiqrQr(Integer appUserId) {

        JSONObject token = WechatUtil.getAccessToken();
//
//        // 使用前端code获取手机号码 参数为json格式
//        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");

        Map<String, Object> retMap = null;
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token.getString("access_token"));
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", appUserId);
            paramJson.put("page", "pages/index/main");
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);


            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            /*ByteArrayOutputStream os = new ByteArrayOutputStream();*/
            OutputStream os = new FileOutputStream(new File("D:/test/2.jpg"));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
//            // 上传到oss
//            String fileName = CurrentTimeMillisId.next() + ".jpg";
//            String urls = createFilePath(fileName, sourceType);
//            InputStream is = new ByteArrayInputStream(os.toByteArray());
//            String miniCodeUrl = ossFileService.uploadFile(is, urls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }


}

